package com.dmcb.trade.business.crawlers.article;

import com.dmcb.common.business.utils.DateUtil;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.entities.Article;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 长江日报文章解析
 * Created by 63221_000 on 2016/8/5 0005.
 */
@Service
public class ChangJiangRiBaoParser extends BaseParser {

    /**
     * 网站URL网址
     *
     * @return 链接
     */
    @Override
    protected String url() {
        return CrawlConstant.CHANGJIANGRIBAO_URL;
    }

    /**
     * 获取标题选择器
     *
     * @return 标题选择器
     */
    @Override
    protected String titleSelect() {
        return "strong[style*=黑体]";
    }

    /**
     * 获取日期选择器
     *
     * @return 发布日期选择器
     */
    @Override
    protected String dateSelect() {
        return "span.default>strong>font";
    }

    /**
     * 获取正文内容选择器
     *
     * @return 正文内容选择器
     */
    @Override
    protected String bodySelect() {
        return "div#ozoom";
    }

    /**
     * 获取封面选择器
     *
     * @return 封面选择器
     */
    @Override
    protected String coverSelect() {
        return "span.px12>table>tbody>tr>td img[src]";
    }

    /**
     * 获取作者选择器
     *
     * @return 作者选择器
     */
    @Override
    protected String authorNameSelect() {
        return "div#ozoom>p";
    }


    @Override
    protected void setAuthorName(Document doc, Article article) {
        Elements elements = doc.select(authorNameSelect());
        if (elements == null || elements.size() == 0) {
            return;
        }
        int index = elements.size()-2;
        Element element = elements.get(index);
        String authorName = text(element);
        if (StringUtils.isNotBlank(authorName)) {
            authorName = authorName.trim().replace("：", "").replace(":", "").substring(1, authorName.length()).replaceAll("\u00A0", "").replace("□","");
            article.setAuthorName(authorName);
        }
    }


    @Override
    protected void setPostDate(Document doc, Article article) {
        Element element = doc.select(dateSelect()).first();
        if (element != null) {
            String time = text(element);
            if (StringUtils.isBlank(time)) {
                return;
            }
            time = time.replace("星期", "").replace(" ", "");
            Date date = DateUtil.parseDate(time);
            if (date != null) {
                article.setPostTime(date);
            }
        }
        super.setPostDate(doc, article);
    }

    @Override
    protected String platform() {
        return "长江日报";
    }
}

